package communication.common;

import game.map.Static;

import java.util.ArrayList;

public class LoggedPlayers {
	
	private ArrayList<LoggedPlayer> loggedPlayers = null;
	ArrayList<Integer> colors = Static.randomColors(6);
	
	public LoggedPlayers() {
		loggedPlayers = new ArrayList<LoggedPlayer>();
	}
	
	public LoggedPlayer get(int index) {
		return loggedPlayers.get(index);
	}
	
	public void addPlayer(LoggedPlayer player) {
		if (!loggedPlayers.contains(player)) {
			player.setColor(colors.get(getNumPlayers()));
			loggedPlayers.add(player);
		}
	}
	
	public void dropPlayer(String name) {
		for (int i = 0; i < loggedPlayers.size(); i++)
			if (loggedPlayers.get(i).getName().equals(name))
				loggedPlayers.remove(i);
	}
	
	public void clear() {
		LoggedPlayer lp = null;
		if (getNumPlayers() > 0)
			lp = loggedPlayers.get(0);
		
		loggedPlayers.clear();
		
		if (getNumPlayers() > 0)
			loggedPlayers.add(lp);
	}
	
	public void setPlayerReady(String playerName, boolean ready) {
		for (int i = 0; i < loggedPlayers.size(); i++)
			if (loggedPlayers.get(i).getName().equals(playerName))
				loggedPlayers.get(i).setReady(ready);
	}

	public int getNumPlayers() {
		return loggedPlayers.size();
	}
	
	public boolean hasPlayer(String name) {
		for (int i = 0; i < getNumPlayers(); i++) {
			if (get(i).getName().equals(name))
				return true;
		}
		return false;
	}
	
	public boolean allReady() {
		for (int i = 0; i < getNumPlayers(); i++) {
			if (!get(i).isReady())
				return false;
		}
		return true;
	}
	
	public ArrayList<String> getPlayersReadyList() {
		ArrayList<String> aux = new ArrayList<String>();
		for (LoggedPlayer player : loggedPlayers) {
			String registro = player.getName();
			if (player.isReady())
				registro = "*" + registro;
			
			aux.add(registro);
		}
		return aux;
	}
	
	public ArrayList<String> getPlayersChatList(String self) {
		ArrayList<String> aux = new ArrayList<String>();
		if (!self.equals(CommonData.MASTER))
			aux.add(CommonData.MASTER);
		for (LoggedPlayer player : loggedPlayers) {
			String name = player.getName();
			if (!self.equals(name))
				aux.add(name);
		}
		aux.add(CommonData.ALL_PLAYERS);
		return aux;
	}

}
